<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.plugin.plugin' );
jimport( 'joomla.filesystem.file' );
jimport( 'joomla.filesystem.folder' );

function buildCsscache($optimize, $pathes, $cacheFile) {
	$data = '';
	// Build aggregate CSS file.
	foreach ($pathes as $file) {		
		$contents = getCssFileContent($file, $optimize);		
		$base = basePathForFile($file);
		buildCassPath(NULL, $base);		
		$data .= preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', 'buildCassPath', $contents);		
		$regexp = '/@import[^;]+;/i';
		preg_match_all($regexp, $data, $matches);
		$data = preg_replace($regexp, '', $data);
		$data = implode('', $matches[0]) . $data;
		$data=str_replace(JPATH_ROOT.DS, JURI::base(true).'/' , $data);
	}
	$data = getOutHeader('css').$data ;
	JFile::write($cacheFile, $data) ;
	chmod($cacheFile, 0755) ;
	return true;
}
function buildJsCache($scripts, $jsSingle, $loadPosition) {
	if ($loadPosition == 0) {
		foreach ($scripts as $script) {			
			$fileName = md5(JURI::base().$script).'.php' ;
			$cacheFileName = JPATH_CACHE.DS.'js'.DS.$fileName ;
			if (JFile::exists($script)) {
				$content =  JFile::read($script) ;
				if (strpos($script, 'joomla.javascript.js')!==false or strpos($script,'mambojavascript.js')!==false) {
		              $content = str_replace("// <?php !!", "// ", $content);
		        }		        			
				$content = getOutHeader('js').$content ;
				JFile::write($cacheFileName, $content) ;	
				chmod($cacheFileName, 0755) ;													
			}
		} 
	} else {
		$data='';	
		foreach($scripts as $script) {
			if(JFile::exists($script)){
				$content = JFile::read($script);
				if (strpos($script, 'joomla.javascript.js')!==false or strpos($script,'mambojavascript.js')!==false) {
		              $content = str_replace("// <?php !!", "// ", $content);
		        }						
				$data .= "\n\n".$content;		
			}
		}
		$data = getOutHeader('js').$data ;
		JFile::write($jsSingle, $data) ;
		chmod($jsSingle, 0755) ;	
	}		
 	return true ;
}

function basePathForFile($file=NULL){
	$rootPath = JPATH_ROOT ;
	$baseUrl =  JURI::base(true) . '/' ;	
	$base=str_replace($rootPath, $baseUrl, dirname($file)).'/';
	$base=str_replace("\\\\\\",'/',$base);
	$base=str_replace("///",'/',$base);
	$base=str_replace("/\\/",DS,$base);
	$base=str_replace("\\/\\",DS,$base);
	$base=str_replace("\\",'/',$base);
	$base=str_replace("\\\\",'/',$base);
	$base=str_replace("\\/",'/',$base);
	$base=str_replace("/\\",'/',$base);
	$base=str_replace("//",'/',$base);
	$base=str_replace("/",'/',$base);
	$base=str_replace('http:/','http://',$base);
	$base=str_replace('https:/','https://',$base);
	return $base;
}
function getCssFileContent($file, $optimize = NULL) {
	static $_optimize;	
	if (isset($optimize)) {
		$_optimize = $optimize;
	}
	$contents = '';
	if (file_exists($file)) {		
		$contents = JFile::read($file);		
		$cwd = getcwd();
		chdir(dirname($file));		
		$contents = preg_replace_callback('/@import\s*(?:url\()?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\)?;/', 'getCssFileContentCallback', $contents);		
		$contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
		if ($_optimize) {
			// Perform some safe CSS optimizations.
			$contents = preg_replace('<
        	\s*([@{}:;,]|\)\s|\s\()\s* |  # Remove whitespace around separators, but keep space around parentheses.
        	/\*([^*\\\\]|\*(?!/))+\*/ |   # Remove comments that are not CSS hacks.
        	[\n\r]                        # Remove line breaks.
        	>x', '\1', $contents);
		}		
		chdir($cwd);
	}
	return $contents;
}

function getCssFileContentCallback($matches) {
	$filename = $matches[1];
	$base = dirname(realpath($filename)) .'/';
	buildCassPath(NULL, $base);	
	$file = getCssFileContent($filename);	
	return preg_replace('/url\(([\'"]?)(?![a-z]+:)([^\'")]+)[\'"]?\)?;/i', 'url(\1'. dirname($filename) .'/', $file);
}

function buildCassPath($matches, $base = NULL) {
	static $_base;	
	if (isset($base)) {
		$_base = $base;
	}	
	$path = $_base . $matches[1];
	$last = '';
	while ($path != $last) {
		$last = $path;
		$path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
	}
	return 'url('. $path .')';
}

function isInternal($url) {
	$uri =& JURI::getInstance($url);
	$base = $uri->toString(array('scheme', 'host', 'port', 'path'));
	$host = $uri->toString(array('scheme', 'host', 'port'));
	if(stripos($base, JURI::base()) !== 0 && !empty($host)) {
		return false;
	}
	return true;
}			


function replaceSperator($link){
	$link=str_replace("\\\\",DS,$link);
	$link=str_replace("/\\/",DS,$link);
	$link=str_replace("\\/\\",DS,$link);
	$link=str_replace("\\",DS,$link);
	$link=str_replace("//",DS,$link);
	$link=str_replace("/",DS,$link);
	return $link;
}

function endwith($FullStr, $EndStr)  {	
	$StrLen = strlen($EndStr);
	$FullStrEnd = substr($FullStr, strlen($FullStr) - $StrLen);
	if($FullStrEnd == $EndStr){
		return true;
	}
	return false;
}

function getOutHeader($type="css") {
    if ($type=="css") {	    		    	
   	    $header='<?php 
		ob_start ("ob_gzhandler");
		header("Content-type: text/css; charset: UTF-8");
		header("Cache-Control: must-revalidate");
		$offset = 60 * 60 ;
		$ExpStr = "Expires: " . 
		gmdate("D, d M Y H:i:s",
		time() + $offset) . " GMT";
		header($ExpStr);
              	?>';
    } else {
        $header='<?php 
		ob_start ("ob_gzhandler");
		header("Content-type: application/x-javascript; charset: UTF-8");
		header("Cache-Control: must-revalidate");
		$offset = 60 * 60 ;
		$ExpStr = "Expires: " . 
		gmdate("D, d M Y H:i:s",
		time() + $offset) . " GMT";
		header($ExpStr);
                ?>';
     }
     return $header;
}


function replaceCss($matches,$exclude = NULL){
	static $_exclude;
	// Store exclude css for preg_replace_callback.
	if (isset($exclude)) {
		$_exclude = $exclude;
	}else if(isset($_exclude)){
		$cssRegex="/([^\"\'=]+\.(css))[\"\']/i";		
		if (strpos($matches[0], 'fetchscript.php')) 
		{			
			return $matches[0] ;		
		}		
		preg_match_all($cssRegex, $matches[0], $m);													
		if(isset($m[1])&&count($m[1])){										
			$cssFile=$m[1][0];			
			if(count($_exclude)){
				foreach($_exclude as $exd){
					if($exd&&endwith($cssFile, $exd)){
						return $matches[0];
					}
				}
			}			
			$ignore= count($m[0])&&endwith( $cssFile,'.css')&&!endwith( $cssFile,'.css.php')&&isInternal( $cssFile);
			if($ignore){
				return ' ';
			} else{
				return $matches[0];
			}						
		}else{
			return $matches[0];
		}
	}
}

/**
 * Replace css in body
 *
 * @param array $matches
 * @param array $exclude
 * @param tinyint $type  0 : site, 1  : module , 2 : component 
 * @return string
 */

function replaceJs($matches,$exclude = NULL, $type = 0, $position = 0){
	static $_exclude, $_type, $_position;
	// Store exclude javascripts for preg_replace_callback.
	if (isset($exclude)) {
		$_exclude = $exclude;
		$_type = $type ;
		$_position = $position ;
	}else if(isset($_exclude)){
		$jsRegex="/src=[\"\']([^\"\']+)[\"\']/i";
		preg_match_all($jsRegex, $matches[0], $m);
		if(isset($m[1])&&count($m[1])){
			$scriptFile=$m[1][0];
			if(count($_exclude)){
				foreach($_exclude as $exd){
					if($exd&&endwith($scriptFile, $exd)){
						return $matches[0];
					}
				}
			}
			switch ($_type) {
				case 0 :
					$ignore = count($m[0])&& endwith( $scriptFile,'.js') && !endwith( $scriptFile,'.js.php') && isInternal( $scriptFile) && !(strpos($scriptFile, 'compnents') || strpos($scriptFile, 'modules'));
					break ;
				case 1 :
					$ignore= count($m[0])&&endwith( $scriptFile,'.js')&&!endwith( $scriptFile,'.js.php')&&isInternal( $scriptFile) && strpos($scriptFile, 'modules');					
					break ;	
				case 2 :
					$ignore= count($m[0])&&endwith( $scriptFile,'.js')&&!endwith( $scriptFile,'.js.php')&&isInternal( $scriptFile) && strpos($scriptFile, 'components');
					break ;	
			}						
			if($ignore){
				if ($_position == 0) {
					$cacheFileName = getNameFromLink($scriptFile) ;
					$fileName = md5(JURI::base().$cacheFileName).'.php' ;
					if (JFile::exists(JPATH_CACHE.DS.'js'.DS.$fileName)) {
						$ret = JURI::base(true).'/cache/js/'.$fileName ;
						return '<script language="javascript" type="text/javascript" src="'.$ret.'"></script>' ;
					} else {
						return $matches[0] ;
					}						
				} else {
					return ' ';	
				}				
			} else{
				//Canculate the filename for js file																				
				return $matches[0];
			}
		}else{
			return $matches[0];
		}
	}
}
/**
 * Get name of script from link
 *
 * @param string $script
 * @return string
 */
function getNameFromLink($script) {
	$ret = "" ;
	if(isInternal($script)){			 			
		$parts=@explode( JURI::base(), $script);
		if(count($parts)>1 && strpos($parts[1],'.js')){
			$script = JPATH_ROOT.DS.$parts[1] ;
			$ret = replaceSperator($script);						 				
		}else if(strpos($script,'.js')){	 					
			$script = $_SERVER['DOCUMENT_ROOT'].DS.$script;
			$script = replaceSperator($script);
			if(JFile::exists($script)){	 					
				$ret = $script ;	 						 						 						 					
			}else{
				$script = JPATH_ROOT.DS.$script;
				$script = replaceSperator($script);
				if(JFile::exists($script)){
					$ret = $script ; 						
				}
			}
		}	 					
	}
	return $ret ;	 	
}


/**
 * s5_css_js_compressor plugin
 *
 * @package		s5_css_js_compressor
 * @subpackage	System
 */
class  plgSystems5_css_js_compressor extends JPlugin
{
	/**
	 * Constructor function
	 *
	 * @param string $subject
	 * @param object $config
	 * @return plgSystems5_css_js_compressor
	 */
	function plgSystems5_css_js_compressor(& $subject, $config)
	{
		parent::__construct($subject, $config);
	}
	/**
	 * Process the output buffer, compress css and js files
	 *
	 */
	function onAfterRender()
	{
		global $mainframe;		
		if ($mainframe->isAdmin()) return;
		//Get params						
		$cacheTime = $this->params->get('cache_time', 900);
		$optimizeCss = $this->params->get('optimize_css', 1);				
		$siteCss = $this->params->get('site_css', 1);
		$siteJs = $this->params->get('site_js', 1);
		$siteJsPosition = $this->params->get('site_js_position', 1);				
		$moduleCss = $this->params->get('module_css', 1);
		$moduleJs = $this->params->get('module_js', 1);
		$moduleJsPosition = $this->params->get('module_js_position', 1);		
		$componentCss = $this->params->get('component_css', 1); 
		$componentJs = $this->params->get('component_js', 1);
		$componentJsPosition = $this->params->get('component_js_position', 1);		
		
		$css1Exclude = $this->params->get('css1_exclude');
		$css2Exclude = $this->params->get('css2_exclude');
		$css3Exclude = $this->params->get('css3_exclude');
		$css4Exclude = $this->params->get('css4_exclude');
		$css5Exclude = $this->params->get('css5_exclude');
		$css6Exclude = $this->params->get('css6_exclude');
		$css7Exclude = $this->params->get('css7_exclude');
		$css8Exclude = $this->params->get('css8_exclude');
		$css9Exclude = $this->params->get('css9_exclude');
		$css10Exclude = $this->params->get('css10_exclude');
		
		$js1Exclude = $this->params->get('js1_exclude');
		$js2Exclude = $this->params->get('js2_exclude');
		$js3Exclude = $this->params->get('js3_exclude');
		$js4Exclude = $this->params->get('js4_exclude');
		$js5Exclude = $this->params->get('js5_exclude');
		$js6Exclude = $this->params->get('js6_exclude');
		$js7Exclude = $this->params->get('js7_exclude');
		$js8Exclude = $this->params->get('js8_exclude');
		$js9Exclude = $this->params->get('js9_exclude');
		$js10Exclude = $this->params->get('js10_exclude');
								
		$excludeCss = array() ;
		$excludeJs = array() ;
		$excludeJs[] = 'tiny_mce.js';
		if ($css1Exclude) {
			$excludeCss[] = $css1Exclude ;
		}			
		if ($css2Exclude) {
			$excludeCss[] = $css2Exclude ;
		}		
		if ($css3Exclude) {
			$excludeCss[] = $css3Exclude ;
		}
		if ($css4Exclude) {
			$excludeCss[] = $css4Exclude ;
		}
		if ($css5Exclude) {
			$excludeCss[] = $css5Exclude ;
		}
		if ($css6Exclude) {
			$excludeCss[] = $css6Exclude ;
		}
		if ($css7Exclude) {
			$excludeCss[] = $css7Exclude ;
		}
		if ($css8Exclude) {
			$excludeCss[] = $css8Exclude ;
		}
		if ($css9Exclude) {
			$excludeCss[] = $css9Exclude ;
		}
		if ($css10Exclude) {
			$excludeCss[] = $css10Exclude ;
		}		
		if ($js1Exclude) {
			$excludeJs[] = $js1Exclude ;
		}
		if ($js2Exclude) {
			$excludeJs[] = $js2Exclude ;
		}
		if ($js3Exclude) {
			$excludeJs[] = $js3Exclude ;
		}
		if ($js4Exclude) {
			$excludeJs[] = $js4Exclude ;
		}
		if ($js5Exclude) {
			$excludeJs[] = $js5Exclude ;
		}			
		if ($js6Exclude) {
			$excludeJs[] = $js6Exclude ;
		}
		if ($js7Exclude) {
			$excludeJs[] = $js7Exclude ;
		}		
		if ($js8Exclude) {
			$excludeJs[] = $js8Exclude ;
		}
		if ($js9Exclude) {
			$excludeJs[] = $js9Exclude ;
		}
		if ($js10Exclude) {
			$excludeJs[] = $js10Exclude ;
		}																		
		$body = JResponse::getBody();				
		if ($siteCss || $moduleCss || $componentCss) {
			$stylesheets = $this->_getCssFiles($body, $excludeCss, $siteCss, $moduleCss, $componentCss);						
			$this->_processCSSFiles($stylesheets, $cacheTime,  $optimizeCss, $siteCss, $moduleCss, $componentCss, $body, $excludeCss);			
		}																				
		if ($siteJs || $moduleJs || $componentJs) {			
			$scripts = $this->_getJsFiles($body, $excludeJs, $siteJs, $moduleJs, $componentJs);
			$this->_processJsFiles($scripts, $cacheTime, $siteJs, $moduleJs, $componentJs , $siteJsPosition, $moduleJsPosition, $componentJsPosition ,$body, $excludeJs);
		}			
		JResponse::setBody($body);
	}
	/**
	 * Get list of css files
	 *
	 * @return array
	 */
	function _getCssFiles($body, & $excludeCss, $siteCss, $moduleCss, $componentCss) {		 				
		//Links tags regular expression		
		$linksRegex="|<link[^>]+[/]?>((.*)</[^>]+>)?|U";
		//css files regular expression
		$cssRegex="/([^\"\'=]+\.(css))[\"\']/i";						
		$matches = null ;						 		
	 	preg_match_all($linksRegex, $body, $matches);
	 	$links = @implode('', $matches[0]);	 		 	
	 	preg_match_all($cssRegex, $links, $matches);
	 	$cssLinks= array();	 		 		 	
	 	foreach($matches[1] as $link){	 				 		 		
	 		if(isInternal($link)){				
	 			$originalLink = $link ;	 	 				 				 				 			
	 			$parts=@explode( JURI::base(),$link);
	 			if(count($parts) > 1 && strpos($parts[1],'.css')){
	 				$link = JPATH_ROOT.DS.$parts[1];
	 				$link = replaceSperator($link);
	 				$cssLinks[] = $link;	 				
	 			}else if(strpos($link,'.css')){
	 				$link = $_SERVER['DOCUMENT_ROOT'].DS.$link;	 					 				
	 				$link = replaceSperator($link);
	 				if(JFile::exists($link)){
	 					$cssLinks[] = $link;	 					
	 				}else{	 						 											
	 					$link = JPATH_ROOT.DS.$originalLink;	 						 					
	 					$link = replaceSperator($link);
	 					if(JFile::exists($link)){
	 						$cssLinks[] = $link;	 						
	 					}
	 				}
	 			}	 				 			
	 			if (!$siteCss && ! (strpos($originalLink, 'modules')!==false || strpos($originalLink, 'components') !== false)) {
	 				$excludeCss[] = $originalLink ;		 			
	 			}
	 			
	 			if (!$moduleCss && strpos($originalLink, 'modules') !== false){
	 				$excludeCss[] = $originalLink ; 
	 			}	 				 												 				 				 			
	 			if (!$componentCss && strpos($originalLink, 'components') !== false) {					
	 				$excludeCss[] = $originalLink ;
	 			}
	 		}	 		
	 	}	 	
	 	$cssLinks = array_unique($cssLinks) ;	 		 		 		 
		return $cssLinks ;
	}
	/**
	 * Get list of css files
	 *
	 * @return string
	 */		
	function _getJsFiles($body, & $excludeJs, $siteJs, $moduleJs, $componentJs) {
		$matches = null ;						
		$scriptRegex = "/<script [^>]+(\/>|><\/script>)/i";		
	 	$jsRegex = "/([^\"\'=]+\.(js))[\"\']/i";
	 	preg_match_all($scriptRegex, $body, $matches);
	 	$scripts = @implode('', $matches[0]);
	 	preg_match_all($jsRegex, $scripts, $matches);
	 	$scriptFiles= array();
	 	$scriptFiles['site_js'] = array() ;
	 	$scriptFiles['module_js'] = array() ;
	 	$scriptFiles['component_js'] = array(); 
	 	foreach($matches[1] as $script){	 		 		
	 		if(isInternal($script)){	
	 			$originalScript = $script ; 			
	 			$parts=@explode( JURI::base(), $script);
	 			if(count($parts)>1 && strpos($parts[1],'.js')){
	 				$script = JPATH_ROOT.DS.$parts[1] ;
	 				$script = replaceSperator($script);
	 				if (strpos($script, 'components')) {
	 					$scriptFiles['component_js'][] = $script ;
	 				} elseif (strpos($script, 'modules')) {
	 					$scriptFiles['module_js'][] = $script ;
	 				} else {
	 					$scriptFiles['site_js'][] = $script ;
	 				} 				
	 			}else if(strpos($script,'.js')){	 					
	 				$script = $_SERVER['DOCUMENT_ROOT'].DS.$script;
	 				$script = replaceSperator($script);
	 				if(JFile::exists($script)){	 					
		 				if (strpos($script, 'components')) {
		 					$scriptFiles['component_js'][] = $script ;
		 				} elseif (strpos($script, 'modules')) {
		 					$scriptFiles['module_js'][] = $script ;
		 				} else {
		 					$scriptFiles['site_js'][] = $script ;
		 				}	 						 						 						 					
	 				}else{
	 					$script = JPATH_ROOT.DS.$originalScript;
	 					$script = replaceSperator($script);
	 					if(JFile::exists($script)){
	 						if (strpos($script, 'components')) {
			 					$scriptFiles['component_js'][] = $script ;
			 				} elseif (strpos($script, 'modules')) {
			 					$scriptFiles['module_js'][] = $script ;
			 				} else {
			 					$scriptFiles['site_js'][] = $script ;
			 				}	 						
	 					}
	 				}
	 			}	 			
	 			if (!$siteJs && ! (strpos($originalScript, 'modules') || strpos($originalScript, 'components'))) {
	 				$excludeJs[] = $originalScript ;			 			 
	 			}
	 			if (!$moduleJs && strpos($originalScript, 'modules')) {
	 				$excludeJs[] = $originalScript ;
	 			}
	 			if (!$componentJs && strpos($originalScript, 'components')) {
	 				$excludeJs[] = $originalScript ;
	 			}
	 		}	 		
	 	}
	 	$scriptFiles['site_js'] = array_unique($scriptFiles['site_js']) ;
	 	$scriptFiles['module_js'] = array_unique($scriptFiles['module_js']) ;
	 	$scriptFiles['component_js'] = array_unique($scriptFiles['component_js']) ;
	 	return $scriptFiles ;
	}
	/**
	 * Compress js files
	 *
	 * @param array $cssLinks
	 * @param int $cacheTime
	 * @param int $optimizeCss
	 * @param int $siteCss
	 * @param int $moduleCss
	 * @param int $componentCss
	 * @param string $body
	 * @param array $excludeCss
	 */
    function _processCSSFiles($cssLinks, $cacheTime,  $optimizeCss, $siteCss, $moduleCss, $componentCss, &$body, $excludeCss) {	    	    	    	
  		$singlecssFileName = md5(JURI::base().@implode('',$cssLinks)).'.php';	 		
 		$cssBaseDir = JPATH_CACHE.DS.'css';
 		if(!JFile::exists($cssBaseDir)){
 			JFolder::create($cssBaseDir, 0755); 			
 		}
 		$cssSingle = $cssBaseDir.DS.$singlecssFileName;	 		
		if (JFile::exists($cssSingle)) {
    		 $diff = (time()-filectime($cssSingle));
    	} else {
    		 $diff = $cacheTime + 1;
    	} 
    	$ret = true ;    	      	    	
    	if (count($excludeCss)) {    		 
    		 $arr = array();
    		 foreach ($cssLinks as $cssLink) {
    		 	$ignore = false ;
    		 	foreach ($excludeCss as  $exd) {
    		 		if (endwith($cssLink, $exd) && $exd) {
    		 			$ignore = true ;
    		 			break ;   	    	
    		 		}
    		 		if (!$ignore) {
    		 			$arr[] = $cssLink ;
    		 		}
    		 	}
    		 }
    		 $cssLinks = $arr ;
    	}    	    	    	    	    	    	    	    			
   		if ($diff > $cacheTime){
   			$ret = buildCsscache($optimizeCss, $cssLinks, $cssSingle);	        
   		} 		 		 		   		   	   		
 		if($ret){
 			$linksRegex="|<link[^>]+[/]?>((.*)</[^>]+>)?|U";
 			replaceCss(NULL, $excludeCss);
	 		$body = preg_replace_callback($linksRegex, 'replaceCss', $body); 			 				
 			$baseUrl = JURI::base(true).'/' ; 			 			
 			$newImportCss='</title>
					<link  rel="stylesheet" type="text/css" href="'. $baseUrl .'cache/css/'.$singlecssFileName.'"/>';
 			$body = preg_replace('/<\/title>/i',$newImportCss , $body, 1); 			
 		}       
    }    
    /**
     * Process js files
     *
     * @param array $scripts
     * @param int $cacheTime
     * @param int $siteJs
     * @param int $moduleJs
     * @param int $componentJs
     * @param int $siteJsPosition
     * @param int $moduleJsPosition
     * @param int $componentJsPosition
     * @param string $body
     * @param array $excludeJs
     */    
   	function _processJsFiles($scripts, $cacheTime, $siteJs, $moduleJs, $componentJs , $siteJsPosition, $moduleJsPosition, $componentJsPosition , &$body, $excludeJs) {
   		$baseUrl = JURI::base(true).'/' ;
   		$siteJss = $scripts['site_js'];
   		$moduleJss = $scripts['module_js'] ;
   		$componentJss = $scripts['component_js'] ;
   		   		   		
   		$singleSiteJsFileName = md5(JURI::base().@implode('', $siteJss)).'.php';
   		$singleModuleJsFileName = md5(JURI::base().@implode('', $moduleJss)).'.php';
   		$singleComponentJsFileName = md5(JURI::base().@implode('', $componentJss)).'.php';   		
   		   		   		
 		$jsBaseDir = JPATH_CACHE.DS.'js';
 		if(!JFile::exists($jsBaseDir)){
 			JFolder::create($jsBaseDir, 0755) ;	 			
 		}
 		
 		$jsSingleSite = $jsBaseDir.DS.$singleSiteJsFileName ;
   		if (JFile::exists($jsSingleSite)) {
    		 $diffSite = (time()-filectime($jsSingleSite));
    	} else {
    		 $diffSite = $cacheTime + 1;
    	}  
 		
   		$jsSingleModule = $jsBaseDir.DS.$singleModuleJsFileName ;
   		if (JFile::exists($jsSingleModule)) {
    		 $diffModule = (time()-filectime($jsSingleModule));
    	} else {
    		 $diffModule = $cacheTime + 1;
    	}
    	
   		$jsSingleComponent = $jsBaseDir.DS.$singleComponentJsFileName ;
   		if (JFile::exists($jsSingleComponent)) {
    		 $diffComponent = (time()-filectime($jsSingleComponent));
    	} else {
    		 $diffComponent = $cacheTime + 1;
    	}    	    	 			 		    		
    	if (count($excludeJs)) {
    		if (count($siteJss)) {
    			$arr = array() ;	    		    		    		
		    	foreach ($siteJss as $script) {
		    		$ignore = false ;
		    		foreach ($excludeJs as $exd) {
		    			if (endwith($script, $exd) && $exd) {
		    				$ignore = true ;
		    				break ;
		    			}
		    		}
		    		if (!$ignore) {
		    			$arr[] = $script ;
		    		}
		    	}	
		    	$siteJss = $arr ;	
    		}  

    		if (count($moduleJss)) {
    			$arr = array() ;	    		    		    		
		    	foreach ($moduleJss as $script) {
		    		$ignore = false ;
		    		foreach ($excludeJs as $exd) {
		    			if (endwith($script, $exd) && $exd) {
		    				$ignore = true ;
		    				break ;
		    			}
		    		}
		    		if (!$ignore) {
		    			$arr[] = $script ;
		    		}
		    	}	
		    	$moduleJss = $arr ;	
    		}
    		
	    	if (count($siteJss)) {
    			$arr = array() ;	    		    		    		
		    	foreach ($componentJss as $script) {
		    		$ignore = false ;
		    		foreach ($excludeJs as $exd) {
		    			if (endwith($script, $exd) && $exd) {
		    				$ignore = true ;
		    				break ;
		    			}
		    		}
		    		if (!$ignore) {
		    			$arr[] = $script ;
		    		}
		    	}	
		    	$componentJss = $arr ;	
    		}    		
    	}	    		

    	if (count($siteJss) && $siteJs) {
    		if ($diffSite > $cacheTime) {
    			buildJsCache($siteJss, $jsSingleSite, $siteJsPosition);			
    		}
			$scriptRegex = "/<script [^>]+(\/>|><\/script>)/i";
 			replaceJs(NULL, $excludeJs, 0, $siteJsPosition);
 			$body = preg_replace_callback($scriptRegex, "replaceJs", $body);
 			if ($siteJsPosition) { 					 		
 				if ($siteJsPosition == 1) {
 					$newImportJs='</title>
					<script type="text/javascript" src="'. $baseUrl.'cache/js/'.$singleSiteJsFileName.'"></script>'; 			
		 			$body = preg_replace('/<\/title>/i',$newImportJs , $body,1);			 			 			
 				} elseif ($siteJsPosition == 2) {
 					$newImportJs='
					<script type="text/javascript" src="'. $baseUrl.'cache/js/'.$singleSiteJsFileName.'"></script>
					</body>'; 			
		 			$body = preg_replace('/<\/body>/i',$newImportJs , $body,1);	 				 			 			
 				}
 			} 			    		    		
    	}
    	
    	if (count($moduleJss) && $moduleJs) {
    		if ($diffModule > $cacheTime) {
    			buildJsCache($moduleJss, $jsSingleModule, $moduleJsPosition);			
    		}
			$scriptRegex = "/<script [^>]+(\/>|><\/script>)/i";
 			replaceJs(NULL, $excludeJs, 1, $moduleJsPosition);
 			$body = preg_replace_callback($scriptRegex, "replaceJs", $body);
 			if ($moduleJsPosition) { 					 		
 				if ($moduleJsPosition == 1) {
 					$newImportJs = '</title>
					<script type="text/javascript" src="'. $baseUrl.'cache/js/'.$singleModuleJsFileName.'"></script>'; 			
		 			$body = preg_replace('/<\/title>/i',$newImportJs , $body,1);			 			 			
 				} elseif ($moduleJsPosition == 2) {
 					$newImportJs='
					<script type="text/javascript" src="'. $baseUrl.'cache/js/'.$singleModuleJsFileName.'"></script>
					</body>'; 			
		 			$body = preg_replace('/<\/body>/i',$newImportJs , $body,1);	 				 			 			
 				}
 			} 			
    	}

   		if (count($componentJss) && $componentJs) {
    		if ($diffComponent > $cacheTime) {
    			buildJsCache($componentJss, $jsSingleComponent, $componentJsPosition);			
    		}
			$scriptRegex = "/<script [^>]+(\/>|><\/script>)/i" ;
 			replaceJs(NULL, $excludeJs, 2, $componentJsPosition);
 			$body = preg_replace_callback($scriptRegex, "replaceJs", $body);	 				 			 			
 			$newImportJs='</title>
			<script type="text/javascript" src="'. $baseUrl.'cache/js/'.$jsSingleComponent.'"></script>'; 			
 			$body = preg_replace('/<\/title>/i',$newImportJs , $body,1);
    	}
    	
    }    				
}				